package com.tfswx.ruleengine.compute.gzjy.felfunc;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pjxq extends BaseFn {

    private static final Pattern DATE_YEAR = Pattern.compile("([\\u4e00-\\u9fa5\\u767e\\u5343\\u96f6]{1,10}年)");

    private static final Pattern DATE_MONTH = Pattern.compile("([\\u4e00-\\u9fa5\\u767e\\u5343\\u96f6]{1,2}月)");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String str = (String) arguments[0];
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            String year = null;
            String month = null;
            int resultMonth = 0;
            Matcher matcher = DATE_YEAR.matcher(str);
            if (matcher.find()) {
                year = matcher.group();
            }
            Matcher matcher1 = DATE_MONTH.matcher(str);
            if (matcher1.find()) {
                month = matcher1.group();
            }
            if (StringUtils.isNotEmpty(year)) {
                year = year.replace("年", "");
                int i = zh2arbaNum(year);
                resultMonth += i * 12;
            }
            if (StringUtils.isNotEmpty(month)) {
                month = month.replace("月", "");
                int i = zh2arbaNum(month);
                resultMonth += i;
            }
            return resultMonth;
        }
    }

    @Override
    public String getZwmc() {
        return "x年x月转换为月";
    }

    @Override
    public boolean isExport() {
        return true;
    }

    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("str"));
        return params;
    }

    @Override
    public String getName() {
        return "convertToMonth";
    }

    private int zh2arbaNum(String zhNumStr) {
        Stack<Integer> stack = new Stack<>();
        String numStr = "一二三四五六七八九";
        String unitStr = "十百千万亿";
        String[] ssArr = zhNumStr.split("");
        for (String e : ssArr) {
            int numIndex = numStr.indexOf(e);
            int unitIndex = unitStr.indexOf(e);
            if (numIndex != -1) {
                stack.push(numIndex + 1);
            } else if (unitIndex != -1) {
                int unitNum = (int) Math.pow(10, unitIndex + 1);
                if (stack.isEmpty()) {
                    stack.push(unitNum);
                } else {
                    stack.push(stack.pop() * unitNum);
                }
            }
        }
        return stack.stream().mapToInt(s -> s).sum();
    }
}
